package com.xxx.yuedong.common.exception;

import com.xxx.yuedong.common.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;


/**
 * 全局异常处理
 *
 * @Author YinXi
 * @Versin 1.0.0
 * @Date 2023/8/3
 */
@Slf4j
@RestControllerAdvice
public class GlobalException {
    /**
     *捕获处理自定义异常
     */
    @ExceptionHandler
    public R yuedongExceptionHandler(YuedongException yuedongException){
        return R.error(yuedongException.getCode(),yuedongException.getMessage());
    }

    /**
     * 处理格式异常信息
     */
    @ExceptionHandler
    public R handleBindException(BindException e) {
        log.debug("全局异常处理器开始处理BindException");
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("请求参数格式错误，");
        stringBuilder.append(e.getFieldError().getDefaultMessage());
        stringBuilder.append("！");
        String message = stringBuilder.toString();
        log.warn(message);
        return R.error(HttpStatus.SC_UNPROCESSABLE_ENTITY,message);
    }

    /**
     * 处理验证异常信息
     */
    @ExceptionHandler
    public R handleConstraintViolationException(ConstraintViolationException e) {
        log.debug("全局异常处理器开始处理ConstraintViolationException");
        StringBuilder stringBuilder = new StringBuilder();
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        for (ConstraintViolation<?> constraintViolation : constraintViolations) {
            stringBuilder.append(constraintViolation.getMessage());
        }
        String message = stringBuilder.toString();
        return R.error(HttpStatus.SC_INTERNAL_SERVER_ERROR, message);
    }
    /**
     * 未知错误异常处理
     */
    @ExceptionHandler
    public R notKonwExceptionHandler(Throwable throwable){
        log.debug("异常信息追踪如下",throwable);
        String msg = "服务器忙请稍后再尝试【观察控制台的报错请求】";
        return R.error(HttpStatus.SC_INTERNAL_SERVER_ERROR,msg).put("errorMessage",throwable.getMessage());
    }

}
